package com.mcc.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcc.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mcc.common.constant.UserConstants;
import com.mcc.common.core.domain.TreeSelect;
import com.mcc.common.core.domain.entity.SysMenu;
import com.mcc.common.utils.SecurityUtils;
import com.mcc.common.utils.StringUtils;
import com.mcc.system.domain.vo.MetaVo;
import com.mcc.system.domain.vo.RouterVo;
import com.mcc.system.mapper.SysMenuMapper;
import com.mcc.system.mapper.SysRoleMenuMapper;
import com.mcc.system.service.ISysMenuService;

/**
 * 菜单 业务层处理
 *
 * @author gxy
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList(new SysMenu(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        //管理员显示所有菜单信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(ObjectUtil.isNotEmpty(menu.getMenuName()), "menu_name", menu.getMenuName());
        queryWrapper.eq(ObjectUtil.isNotEmpty(menu.getVisible()), "visible", menu.getVisible());
        queryWrapper.eq(ObjectUtil.isNotEmpty(menu.getStatus()), "status", menu.getStatus());
        queryWrapper.orderByAsc("parent_id", "order_num");

        //非管理员过滤菜单信息
        if (!SecurityUtils.isAdmin(userId)) {
            QueryWrapper roleWrapper = new QueryWrapper();
            roleWrapper.eq("user_id", userId);
            roleWrapper.select("role_id");
            List<Long> roleIds = userRoleMapper.selectObjs(roleWrapper);
            if (roleIds.size() > 0) {
                QueryWrapper menuWrapper = new QueryWrapper();
                menuWrapper.in("role_id", roleIds);
                menuWrapper.select("distinct menu_id");
                List<Long> menuIds = roleMenuMapper.selectObjs(menuWrapper);
                queryWrapper.in("menu_id", menuIds);
            }
        }
        return menuMapper.selectList(queryWrapper);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        Set<String> permsSet = new HashSet<>();
        QueryWrapper roleWrapper = new QueryWrapper();
        roleWrapper.eq("user_id", userId);
        roleWrapper.select("role_id");
        List<Long> roleIds = userRoleMapper.selectObjs(roleWrapper);
        if (roleIds.size() > 0) {
            QueryWrapper menuWrapper = new QueryWrapper();
            menuWrapper.in("role_id", roleIds);
            menuWrapper.select("distinct menu_id");
            List<Long> menuIds = roleMenuMapper.selectObjs(menuWrapper);
            if (menuIds.size() > 0) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.select("distinct perms");
                queryWrapper.in("menu_id", menuIds);
                List<String> perms = menuMapper.selectObjs(queryWrapper);
                for (String perm : perms) {
                    if (StringUtils.isNotEmpty(perm)) {
                        permsSet.addAll(Arrays.asList(perm.trim().split(",")));
                    }
                }
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("menu_type", ListUtil.list(false, "M", "C"));
        queryWrapper.orderByAsc("parent_id", "order_num");

        if (!SecurityUtils.isAdmin(userId)) {
            QueryWrapper roleWrapper = new QueryWrapper();
            roleWrapper.eq("user_id", userId);
            roleWrapper.select("role_id");
            List<Long> roleIds = userRoleMapper.selectObjs(roleWrapper);
            if (roleIds.size() > 0) {
                QueryWrapper menuWrapper = new QueryWrapper();
                menuWrapper.in("role_id", roleIds);
                menuWrapper.select("distinct menu_id");
                List<Long> menuIds = roleMenuMapper.selectObjs(menuWrapper);
                if (menuIds.size() > 0) {
                    queryWrapper.in("menu_id", menuIds);
                }
            }
        }
        menus = menuMapper.selectList(queryWrapper);
        return getChildPerms(menus, 0);
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        QueryWrapper menuWrapper = new QueryWrapper();
        menuWrapper.eq("role_id", roleId);
        menuWrapper.select("menu_id");
        return roleMenuMapper.selectObjs(menuWrapper);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus, RouterVo fullscreenRouter) {
        List<RouterVo> routers = new LinkedList<>();
        boolean first = fullscreenRouter == null;
        if(first){
            //全屏路由
            fullscreenRouter = new RouterVo();
            fullscreenRouter.setHidden(true);
            fullscreenRouter.setName("全屏");
            fullscreenRouter.setPath("/fullscreen");
            fullscreenRouter.setComponent("common/router");
            fullscreenRouter.setMeta(new MetaVo(fullscreenRouter.getName(), null, false));
            fullscreenRouter.setChildren(new ArrayList<>());
        }
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
            router.setIsNewOpen(menu.getIsNewOpen());
            if (1 == menu.getIsFullscreen()) {
                //全屏跳转
                RouterVo fullscreenChild = new RouterVo();
                fullscreenChild.setHidden(false);
                fullscreenChild.setName(router.getName() + "Fullscreen");
                fullscreenChild.setPath(menu.getPath());
                fullscreenChild.setComponent(router.getComponent());
                fullscreenChild.setMeta(router.getMeta());
                fullscreenChild.setIsNewOpen(router.getIsNewOpen());
                fullscreenRouter.getChildren().add(fullscreenChild);
                router.setRedirect("/fullscreen/" + fullscreenChild.getPath());
            }
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus, fullscreenRouter));
                router.setIsNewOpen(menu.getIsNewOpen());
            } else if (isMeunFrame(menu)) {
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
                children.setIsNewOpen(menu.getIsNewOpen());
                childrenList.add(children);
                router.setChildren(childrenList);
                /*if (1 == menu.getIsFullscreen()) {
                    //一级菜单全屏
                    router = children;
                    router.setPath("/" + router.getPath());
                } else {
                    childrenList.add(children);
                    router.setChildren(childrenList);
                }*/
            }
            routers.add(router);
        }
        if (first) {
            routers.add(fullscreenRouter);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMenu menu = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", menuId);
        return menuMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 新增菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(SysMenu menu) {
        return menuMapper.insert(menu);
    }

    /**
     * 修改菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(SysMenu menu) {
        return menuMapper.updateById(menu);
    }

    /**
     * 删除菜单信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteById(menuId);
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMeunFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeunFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && (!isMeunFrame(menu) || NumberUtil.equals(menu.getIsFullscreen(), 1))) {
            component = menu.getComponent();
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMeunFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
